package cn.hls.service.impl;

import java.io.Serializable;
import java.lang.reflect.Method;

import javax.annotation.Resource;

import cn.hls.dao.BaseDao;
import cn.hls.service.BaseService;
import cn.hls.until.GenericsUtils;

/**
 * @fileName: BaseServiceBean.java
 * @descrption: 基类Service接口实现类
 * @author : yinghui.zhang
 * @Email: uuhui@163.com
 * @date 2015-4-8
 * @version 1.0
 */
public class BaseServiceBean<T> implements BaseService<T> {
	@Resource(name = "baseDaoImpl")
	private BaseDao<T> dao;
	private Class<T> entityClass = null;

	@SuppressWarnings("unchecked")
	public BaseServiceBean() {
		this.entityClass = (Class<T>) GenericsUtils.getSuperClassGenricType(getClass(), 0);
	}

	/**
	 * 持久化实例对象
	 * 
	 * @param entity
	 *            实例对象
	 * @return boolean
	 */

	public boolean add(T entity) throws Exception {
		setEntityId(entity);
		return dao.add(entity);
	}

	/**
	 * 更新实例化对象
	 * 
	 * @param entity
	 *            实例对象 d * @return boolean
	 */
	public boolean update(T entity) throws Exception {
		return dao.update(entity);
	}

	/**
	 * 删除实例化对象
	 * 
	 * @param entityId
	 *            编号
	 * @return boolean
	 */
	public void delete(Object entityId) throws Exception {
		dao.delete(entityId, this.entityClass);

	}

	@Override
	public void deltedByIds(Object[] ids) throws Exception {
		for (Object id : ids) {
			delete(id);
		}

	}

	 

	/**
	 * 根据编号查询实例信息
	 * 
	 * @param entityName
	 *            实例名称
	 * @param entityId
	 *            编号
	 * @return T
	 */
	public T find(Serializable entityId) throws Exception {
		return dao.find(entityId, this.entityClass);
	}

	/**
	 * 通过反射获取对象的id值
	 * 
	 * @param entity
	 *            实例化对象
	 * @return Object
	 */
	@SuppressWarnings("unused")
	private Object getEntityId(T entity) throws Exception {
		Method getIdMethod = null;
		Object resultObject = null;
		try {
			getIdMethod = this.entityClass.getMethod("getId");
			resultObject = getIdMethod.invoke(entity);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw ex;
		}
		return resultObject;
	}
	/**
	 * 动态调用setId方法赋值
	 * @param entity 类对象
	 * @throws Exception 异常
	 */
	private void setEntityId(T entity) throws Exception{
		Method setIdMethod=null;
		setIdMethod=this.entityClass.getSuperclass().getDeclaredMethod("setId", Long.class);
		setIdMethod.invoke(entity, dao.getCustomerId());
	}
}
